import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:study_online/test.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

import 'package:flutter/material.dart';
import 'package:study_online/entity/CourseItemEn.dart';
import 'package:study_online/global/colors.dart';

import '../HomeModel.dart';
import 'RecommendSkeleton.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        //appBar: AppBar(
        //  backgroundColor: Colors.black26,
        //  title: Text('container'),
        //),
        body: RecommendTab(),
      ),
    );
  }
}

class RecommendTab extends StatefulWidget {
  RecommendTab({Key key}) : super(key: key);

  @override
  _RecommendTabState createState() {
    return _RecommendTabState();
  }
}

class _RecommendTabState extends State<RecommendTab>
    with AutomaticKeepAliveClientMixin {
  CourseItemEnList _courseItemEnList = new CourseItemEnList([]);
  List<CourseItemEn> _siLiuData = [],
      _postgraduateData = [],
      _techniqueData = [];
  CourseItemEn _courseItemEn;
  List<String> imgList = [
    'https://img1.baidu.com/it/u=1232582182,1749710819&fm=26&fmt=auto',
    'https://img1.baidu.com/it/u=4012696096,4169286569&fm=26&fmt=auto',
  ];

  void _loadData() async {
    EasyLoading.show(
      status: "Loading...",
      //maskType: EasyLoadingMaskType.black,
    );
    await Future.delayed(Duration(milliseconds: 2000), () async {
      Response response = await getHomePageCouse();
      print("###" + response.toString());
      var responseData = json.decode(response.toString());
      setState(() {
        _courseItemEnList = CourseItemEnList.formJson(responseData);
        _siLiuData.clear();
        for (int i = 0; i < 4; ++i) {
          _siLiuData.add(_courseItemEnList.data[i]);
        }
        _postgraduateData.clear();
        for (int i = 4; i < 8; ++i) {
          _postgraduateData.add(_courseItemEnList.data[i]);
        }
        _techniqueData.clear();
        for (int i = 8; i < 12; ++i) {
          _techniqueData.add(_courseItemEnList.data[i]);
        }
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _loadData();
    // _courseItemEn = new CourseItemEn(
    //     '四六级专题',
    //     188.0,
    //     'https://img1.baidu.com/it/u=3396838262,522903359&fm=26&fmt=auto&gp=0.jpg',
    //     1,
    //     300);
    // _siLiuData.add(_courseItemEn);
    // _siLiuData.add(_courseItemEn);
    // _siLiuData.add(_courseItemEn);
    // _siLiuData.add(_courseItemEn);
    // _postgraduateData.add(_courseItemEn);
    // _postgraduateData.add(_courseItemEn);
    // _postgraduateData.add(_courseItemEn);
    // _postgraduateData.add(_courseItemEn);
    // _techniqueData.add(_courseItemEn);
    // _techniqueData.add(_courseItemEn);
    // _techniqueData.add(_courseItemEn);
    // _techniqueData.add(_courseItemEn);
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget _swiperWidget() {
    return Container(
      width: double.infinity,
      height: ScreenUtil().setHeight(362),
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setHeight(20),
          top: ScreenUtil().setHeight(10)),
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.network(
              imgList[index],
              fit: BoxFit.cover,
            ),
          );
        },
        pagination: SwiperPagination(
          alignment: Alignment.bottomRight,
          builder: SwiperCustomPagination(
            builder: (BuildContext context, SwiperPluginConfig config) {
              return CustomP(config.activeIndex, imgList.length);
            },
          ),
        ),
        itemCount: imgList.length,
        autoplay: true,
        onIndexChanged: (int index) {
          // Provider.of<SetBgProvider>(context).setBgColor(index);
        },
      ),
    );
  }

  Widget _topWidget() {
    return Container(
      width: double.infinity,
      height: ScreenUtil().setHeight(220),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(60)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(200),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/img/vip_home.png',
                  width: ScreenUtil().setHeight(120),
                  height: ScreenUtil().setHeight(120),
                  fit: BoxFit.fitHeight,
                ),
                Text(
                  'vip特权',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.black,
                  ),
                )
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(200),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipOval(
                  child: Image.asset(
                    'assets/img/hot_recommend.png',
                    width: ScreenUtil().setHeight(120),
                    height: ScreenUtil().setHeight(120),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  '好课推荐',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.black,
                  ),
                )
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(200),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipOval(
                  child: Image.asset(
                    'assets/img/rank.png',
                    width: ScreenUtil().setHeight(120),
                    height: ScreenUtil().setHeight(120),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  '排行榜',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.black,
                  ),
                )
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(200),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipOval(
                  child: Image.asset(
                    'assets/img/all.png',
                    width: ScreenUtil().setHeight(120),
                    height: ScreenUtil().setHeight(120),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  '全部课程',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.black,
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _titleWidget(value, num) {
    return Container(
      margin: EdgeInsets.fromLTRB(
        ScreenUtil().setWidth(46),
        ScreenUtil().setHeight(50),
        ScreenUtil().setWidth(0),
        ScreenUtil().setHeight(0),
      ),
      height: ScreenUtil().setHeight(74),
      child: Stack(
        children: [
          Positioned(
            bottom: 0,
            left: 0,
            child: Container(
              height: ScreenUtil().setHeight(14),
              width: ScreenUtil().setWidth(47) * num,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                    Radius.circular(ScreenUtil().setHeight(7))),
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.center,
                  stops: [0.0, 1.0],
                  colors: [AppColors.primary, Color(0x542DCA97)],
                ),
              ),
            ),
          ),
          Positioned(
            left: 0,
            top: 0,
            child: Text(
              value,
              style: TextStyle(
                fontSize: ScreenUtil().setSp(52),
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Positioned(
              bottom: 0,
              right: 0,
              child: Padding(
                padding: EdgeInsets.only(right: ScreenUtil().setWidth(35)),
                child: Text(
                  '查看全部>',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(45),
                    color: AppColors.subtext,
                  ),
                ),
              ))
        ],
      ),
    );
  }

  Widget _courseItemWidget(CourseItemEn courseItemEn) {
    var itemWidth = (ScreenUtil().screenWidth - 30) / 2;
    if (_courseItemEnList.data.length == 0) {
      return Container(
        width: 0,
        height: 0,
      );
    } else {
      return InkWell(
        onTap: () {
          Navigator.pushNamed(context, 'courseDetail', arguments: [
            courseItemEn.name,
            courseItemEn.cover,
            courseItemEn.price,
            courseItemEn.couId,
          ]);
        },
        child: Container(
          width: itemWidth, //实现在wrap中平铺,高度自适应
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black26,
                offset: Offset(-1, 1.0),
                blurRadius: 1.0,
                spreadRadius: 0.6,
              ),
            ],
            borderRadius: BorderRadius.all(Radius.circular(8)),
          ),
          child: Column(
            children: <Widget>[
              Container(
                width: double.infinity,
                child: AspectRatio(
                  aspectRatio: 2 / 1, //防止服务器返回的图片高度不一致
                  child: ClipRRect(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(8),
                      topRight: Radius.circular(8),
                    ),
                    child: Image.network(
                      courseItemEn.cover,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: ScreenUtil().setHeight(20),
              ),
              Align(
                alignment: Alignment.bottomLeft,
                child: Text(
                  courseItemEn.name,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.black54,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(
                  top: ScreenUtil().setHeight(20),
                ),
                child: Row(
                  children: <Widget>[
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '￥${courseItemEn.price}',
                        style: TextStyle(
                          color: Colors.red,
                          fontSize: 16,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Icon(
                            Icons.group_sharp,
                            size: ScreenUtil().setSp(45),
                            color: Colors.black54,
                          ),
                          SizedBox(
                            width: ScreenUtil().setWidth(18),
                          ),
                          Text(
                            courseItemEn.num.toString(),
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(45),
                              color: Colors.black38,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );
    if (_courseItemEnList.data.length == 0) {
      return EasyRefresh(
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        header: MaterialHeader(),
        onRefresh: () async {
          _loadData();
        },
        onLoad: () async {
          _loadData();
        },
        child: RecommendSkeleton(),
      );
    }
    return EasyRefresh(
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      header: MaterialHeader(),
      footer: MaterialFooter(),
      onRefresh: () async {
        _loadData();
      },
      onLoad: () async {
        _loadData();
      },
      child: ListView(
        children: AnimationConfiguration.toStaggeredList(
          duration: const Duration(milliseconds: 575),
          childAnimationBuilder: (widget) => SlideAnimation(
            horizontalOffset: MediaQuery.of(context).size.width / 2,
            child: FadeInAnimation(child: widget),
          ),
          children: [
            _swiperWidget(),
            _topWidget(),
            _titleWidget('四六级专题', 5),
            Container(
              padding: EdgeInsets.all(10),
              child: Wrap(
                runSpacing: 10,
                spacing: 10,
                children: _siLiuData
                    .asMap()
                    .keys
                    .map((index) => _courseItemWidget(_siLiuData[index]))
                    .toList(),
              ),
            ),
            _titleWidget('考研课', 3),
            Container(
              padding: EdgeInsets.all(10),
              child: Wrap(
                runSpacing: 10,
                spacing: 10,
                children: _postgraduateData
                    .asMap()
                    .keys
                    .map((index) => _courseItemWidget(_postgraduateData[index]))
                    .toList(),
              ),
            ),
            _titleWidget('技能课', 3),
            Container(
              padding: EdgeInsets.all(10),
              child: Wrap(
                runSpacing: 10,
                spacing: 10,
                children: _techniqueData
                    .asMap()
                    .keys
                    .map((index) => _courseItemWidget(_techniqueData[index]))
                    .toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class CustomP extends StatelessWidget {
  var _currentIndex;
  int maxnum;

  CustomP(this._currentIndex, this.maxnum);

  @override
  Widget build(BuildContext context) {
    //debugPaintSizeEnabled=true;
    return Container(
      width: 0.05 * ScreenUtil().screenWidth * maxnum,
      height: ScreenUtil().setHeight(3),
      child: GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: this.maxnum,
            childAspectRatio: 2 / 1,
            crossAxisSpacing: ScreenUtil().setWidth(4)),
        itemBuilder: (BuildContext context, int index) {
          return Container(
            decoration: BoxDecoration(
                color:
                    _currentIndex == index ? Color(0xffF2453E) : Colors.white,
                borderRadius: BorderRadius.circular(1)),
          );
        },
        itemCount: this.maxnum,
      ),
    );
  }
}
